package jdmx.framework.common.serialization;

import java.util.List;

import jdmx.library.da.Sorter;
import jdmx.library.da.SorterField;

import org.jdom.Element;

public class XmlSerializerForSorter implements XmlSerializer {

	@Override
	public Element serialize(Object envelopeItem, String elementName) {
		Sorter sorter = (Sorter) envelopeItem;
		if (sorter == null) return null;
		Element xmlSorter = new Element(elementName);
		for (SorterField field : sorter.getFields()) {
			Element xmlField = new Element(field.name);
			xmlField.setText(field.direction);
			xmlSorter.addContent(xmlField);
		}
		return xmlSorter;
	}

	@Override
	public Sorter deserialize(Element element) {
		Sorter sorter = new Sorter();
		@SuppressWarnings("unchecked") 
		List<Element> xmlChildren = element.getContent();
		for (Element xmlChild : xmlChildren) {
			String fieldName = xmlChild.getName();
			String direction = xmlChild.getText();
			sorter.addField(fieldName, direction);
		}
		return sorter;
	}

}
